package com.itheima.Service.ServiceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.Service.DishService;
import com.itheima.bean.*;
import com.itheima.common.R;
import com.itheima.dao.*;
import com.itheima.dto.DishDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DishServiceImpl implements DishService {

    @Autowired
    private DishDao dishDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private DishFlavorDao dishFlavorDao;

    @Autowired
    private SetmealDishDao setmealDishDao;


    /**
     * 根据分类id查询菜品数据
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishDto> findByCategoryId(long categoryId,int status) {

        //构建条件对象
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();

        //设置条件
        lqw.eq(Dish::getCategoryId, categoryId);

        lqw.eq(status!=0,Dish::getStatus,status);

        List<Dish> dishes = dishDao.selectList(lqw);
        List<DishDto> collect = dishes.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            LambdaQueryWrapper<DishFlavor> df = new LambdaQueryWrapper<>();
            df.eq(DishFlavor::getDishId, dish.getId());
            dishDto.setFlavors(dishFlavorDao.selectList(df));
            return dishDto;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 分页查询加模糊查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<DishDto> findPage(int page, int pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
        dlqw.like(name != null, Dish::getName, name);
        dishDao.selectPage(dishPage, dlqw);
        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<DishDto> collect = dishPage.getRecords().stream().map(dish -> {
            Category category = categoryDao.selectById(dish.getCategoryId());
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(collect);
        return dishDtoPage;
    }

    /**
     * 新增菜品表
     * 先将菜品表数据从dishDto取出封装并保存
     * 再保存口味表
     *
     * @param dishDto
     * @return
     */
    @Override
    public boolean addDish(DishDto dishDto) {
        try {
            Dish dish = new Dish();
            BeanUtils.copyProperties(dishDto, dish);
            dish.setCode("123");
            dish.setSort(13);
            dishDao.insert(dish);
//        System.out.println("dish = " + dish);
            dishDto.getFlavors().stream().forEach(flavor -> {
                flavor.setDishId(dish.getId());
                System.out.println("flavor = " + flavor);
                dishFlavorDao.insert(flavor);
            });
            return true;
        } catch (BeansException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishDto findById(Long id) {
        Dish dish = dishDao.selectById(id);
        LambdaQueryWrapper<DishFlavor> df = new LambdaQueryWrapper<>();
        df.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavors = dishFlavorDao.selectList(df);
        Category category = categoryDao.selectById(dish.getCategoryId());
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setCategoryName(category.getName());
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    /**
     * 修改菜品销售状态
     *
     * @return
     */
    @Override
    public boolean updateStatus(Long[] ids, int status) {
        Dish dish = new Dish();
        dish.setStatus(status);
        try {
            for (Long id : ids) {
                dish.setId(id);
                dishDao.updateById(dish);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 菜品表更新
     *
     * @param dishDto
     * @return
     */
    @Override
    public boolean updateDish(DishDto dishDto) {
        try {
            Dish dish = new Dish();
            BeanUtils.copyProperties(dishDto, dish);
            LambdaQueryWrapper<DishFlavor> df = new LambdaQueryWrapper<>();
            df.eq(DishFlavor::getDishId, dish.getId());
            dishFlavorDao.delete(df);
            dishDto.getFlavors().stream().forEach(flavor -> {
                flavor.setDishId(dish.getId());
                dishFlavorDao.insert(flavor);
            });
            return true;
        } catch (BeansException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据id删除菜品
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteByIds(Long[] ids) {
//        是否需要做删除前的判断
        try {
            int count=0;
            for (Long id : ids) {
                LambdaQueryWrapper<SetmealDish> slqw = new LambdaQueryWrapper<>();
                slqw.eq(SetmealDish::getDishId,id);
                count += setmealDishDao.selectCount(slqw);
            }
            if (count>0){
                return -1;
            }
            dishDao.deleteBatchIds(Arrays.asList(ids));
            for (Long id : ids) {
                LambdaQueryWrapper<DishFlavor> df = new LambdaQueryWrapper<>();
                df.eq(DishFlavor::getDishId,id);
                dishFlavorDao.delete(df);
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }


    }


}
